package it.polimi.traveldream.ejb.acquistomanagement;

import java.util.List;

import it.polimi.traveldream.ejb.pacchettomanagement.Pacchetto;
import it.polimi.traveldream.ejb.usermanagement.User;

import javax.annotation.Resource;
import javax.ejb.EJBContext;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

@Stateless
public class AcquistoMgrBean implements AcquistoMgr {

	@PersistenceContext
    private EntityManager em;
	
	@Resource
	private EJBContext context;
	
	@Override
	public void save(AcquistoDTO acquisto, int idPacchetto) {
		
		Query qP = em.createNamedQuery("Pacchetto.TROVA");
		qP.setParameter("idPacchetto", idPacchetto);
		Pacchetto pacchettox = (Pacchetto) qP.getSingleResult();
		
		Query qU = em.createNamedQuery("User.FIND");
		qU.setParameter("username", getPrincipalUser().getUsername());
		User utente = (User) qU.getSingleResult();
		
		Acquisto newA = new Acquisto();
		
		newA.setNumPosti(acquisto.getNumPosti());
		float prezzotemp = pacchettox.getPrezzo();
		newA.setPrezzo(newA.getNumPosti()*prezzotemp);
		newA.setUtente(utente);
		newA.setPacchetto(pacchettox);
		
		em.persist(newA);
	}

	@Override
	public void remove(AcquistoDTO nuovo) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public List<?> findByUser() {
		Query q = em.createNamedQuery("Acquisto.findAcquisti"); 
		q.setParameter("username", getPrincipalUser().getUsername());
		System.out.println("num: "+q.getResultList().size());
		return q.getResultList();
		
	}
	
	public User trova(String username){
		return em.find(User.class, username);
	}
	
	public User getPrincipalUser(){
		return trova(getPrincipalUsername());
	}
	
	public String getPrincipalUsername(){
		return context.getCallerPrincipal().getName();
	}

}
